'use strict';

function isObject(o) {
  return Object.prototype.toString.call(o) === '[object Object]'
}

function spinnerStart(message = 'processing', spinnerString = '|/-\\') {
  const Spinner = require('cli-spinner').Spinner;
  const spinner = new Spinner(`${message}.. %s`);
  spinner.setSpinnerString(spinnerString);
  spinner.start();
  return spinner;
}

// 进程延迟执行
function sleep(timeout = 1000) {
  return new Promise(resolve => setTimeout(resolve, timeout))
}

function exec(command, args, options) {
  const win32 = process.platform === 'win32';
  const cmd = win32 ? 'cmd' : command;
  const cmdArgs = win32 ? ['/c'].concat(command, args) : args;
  // window: cp.spawn('cmd', ['/c', 'node', '-e', code], { ...options })
  // macOS: cp.spawn('node', ['-e', code], { ...options })
  return require('child_process').spawn(cmd, cmdArgs, options || {});
}

function execAsync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(command, args, options);
    p.on('error', err => {
      reject(err);
    })
    p.on('exit', res => {
      resolve(res);
    })
  });
}

module.exports = {
  isObject,
  spinnerStart,
  sleep,
  exec,
  execAsync
};
